package com.appspot.bs24event.controller;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.log4j.Logger;
import org.slim3.controller.BaseController;
import org.slim3.controller.Navigation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.appspot.bs24event.model.Event;
import com.appspot.bs24event.service.EventService;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.photos.UserFeed;

/**
 * IndexController.
 *
 * @version $Id: IndexController.java 154 2011-07-26 02:57:46Z bs24event@gmail.com $
 */
public class IndexController extends BaseController {

    /** ログ */
    protected static final Logger logger = Logger.getLogger(IndexController.class.getName());

    /** リソースバンドル */
    private static ResourceBundle settingProperties = ResourceBundle.getBundle("setting");

    private EventService service = new EventService();

    @Override
    protected Navigation setUp() {
        logger.info(this.getClass().getName() + " start.");
        return super.setUp();
    }

    @Override
    protected void tearDown() {
        logger.info(this.getClass().getName() + " end.");
        super.tearDown();
    }

    @Override
    public Navigation run() throws Exception {
        // これからのイベント一覧の取得
        List<Event> eventList = service.getList();
        if ( eventList != null  &&  ! eventList.isEmpty() ) {
            requestScope("recentlyEvent", eventList.get(0));
        }

        //-----------------------------
        // Picasaウェブアルバム
        //-----------------------------
        // プロパティ値を取得
        String applicationName   = settingProperties.getString("application.name");
        String googleAccountId   = settingProperties.getString("google.account.id");
        String googleAccountPass = settingProperties.getString("google.account.pass");
        String albumFeedUrl      = settingProperties.getString("album.feed.url");
        try {
            // Picasaウェブアルバムに接続
            PicasawebService myService = new PicasawebService(applicationName);
            myService.setUserCredentials(googleAccountId, googleAccountPass);
            URL feedUrl = new URL(albumFeedUrl);
            UserFeed myUserFeed = myService.getFeed(feedUrl, UserFeed.class);

            // リクエストアトリビュートの設定
            request.setAttribute("myAlbums", myUserFeed.getAlbumEntries());
        } catch (Exception e) {
            logger.warn("Picasaウェブアルバム接続時にエラーが発生しました。",e);
        }
        //-----------------------------
        // USTREAM API
        //-----------------------------
        String ustreamUrl    = settingProperties.getString("ustream.url");
        String ustreamDevKey = settingProperties.getString("ustream.dev.key");
        URL url = new URL(ustreamUrl + ustreamDevKey);
        HttpURLConnection urlConnection = null;
        Document doc = null;
        try {
            urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            // XML取得
            DocumentBuilder docbuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            doc = docbuilder.parse(urlConnection.getInputStream());

            // XMLのresult要素から埋め込用HTMLを取得
            Element root = doc.getDocumentElement();
            NodeList nodeList = root.getElementsByTagName("results");
            if ( 0 < nodeList.getLength() ) {
                request.setAttribute("ustream", nodeList.item(0).getTextContent());
            }
        } catch (Exception e) {
            logger.warn("USTREAM API接続時にエラーが発生しました。",e);
        } finally {
            if (urlConnection != null) urlConnection.disconnect();
        }

        // TOP画面へ遷移
        return forward(request, "index.jsp");
    }
}
